axios 设置了 withCredentials = true 但还是不能带上 cookie 的问题 您所在的位置:网站首页 springboot post请求没有携带cookie axios 设置了 withCredentials = true 但还是不能带上 cookie 的问题

axios 设置了 withCredentials = true 但还是不能带上 cookie 的问题

2024-06-26 23:46| 来源: 网络整理| 查看: 265

axios 设置了withCredentials = true 但还是不能带上cookie的问题 问题背景问题原因解决办法

问题背景

axios 通过 withCredentials = true,让请求来携带 cookie,但浏览器依旧无法携带 cookie 报错信息 在这里插入图片描述

问题原因

简单的来说就是出现了跨域请求,但浏览器默认的SameSite=Lax是不支持跨域下cookie操作的。因此设置cookie失败。

解决办法

解决方法有很多,有通过代码解决的,可以通过设置浏览器来解决,但是不能要求所有用户都改浏览器设置

1. 更改浏览器 链接:https://pan.baidu.com/s/1x3bAMj_4kaJvnpmAouMzaQ 提取码:rwvv

打开谷歌浏览器,地址栏输入:chrome://extensions/然后打开开发者模式,把下载的拖进去

更详细的各个版本的解决方法看这里:完美解决Chrome Cookie SameSite跨站限制

2. 代码解决 方法一:添加一个SpringSession配置类

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.session.web.http.CookieSerializer; import org.springframework.session.web.http.DefaultCookieSerializer; /** * spring-session配置 * 将SameSite = Lax置为None * Secure = true 解决 * @description 解决SameSite=Lax导致前端无法携带Cookie的坑 * @date 2023/4/4 20:14 */ @Configuration public class SpringSessionConfig { public SpringSessionConfig() { } @Bean public CookieSerializer httpSessionIdResolver() { DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); // 取消仅限同一站点设置 cookieSerializer.setSameSite("None"); // 虽然设置了SameSite=None,但是还要设置Secure=true,浏览器才会携带cookie cookieSerializer.setUseSecureCookie(true); return cookieSerializer; } }

方法二:在yml配置文件中添加配置

server: port: 8080 servlet: context-path: /api session: cookie: domain: localhost same-site: none secure: true


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有